package com.wangtao.netty.websocket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class MyTextWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame>{

    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("服务端收到消息:" + msg.text());

        //获取到当前channel
        Channel channel = ctx.channel();
        channelGroup.forEach(ch->{
            if (channel != ch) {
                ch.writeAndFlush(new TextWebSocketFrame("服务器时间 " + LocalDateTime.now().format(dateTimeFormatter) +"\t[客户端] "+
                        ch.remoteAddress().toString().substring(1) +"说: "+ msg.text()+"\n"));
            }else {
                ch.writeAndFlush(new TextWebSocketFrame("服务器时间 " + LocalDateTime.now().format(dateTimeFormatter) +
                        " [自己]: " + msg.text()+"\n"));
            }

        });

    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //asLongText唯一  asShortText不唯一
//        System.out.println("handlerAdded被调用"+ctx.channel().id().asLongText());
//        System.out.println("handlerAdded被调用"+ctx.channel().id().asShortText());

        Channel channel = ctx.channel();
        //该客户端加入聊天信息推送给其他客户端
        channelGroup.add(channel);
        channelGroup.writeAndFlush(new TextWebSocketFrame(LocalDateTime.now().format(dateTimeFormatter)+"\t"+"[客户端]" + channel.remoteAddress() + "加入聊天\t"+"当前在线人数:"+channelGroup.size()+"\n"));
        System.out.println("当前在线人数:"+channelGroup.size());

    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        // System.out.println("handlerRemoved 被调用" + ctx.channel().id().asLongText());
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush(new TextWebSocketFrame(LocalDateTime.now().format(dateTimeFormatter)+"\t"+"[客户端]" + channel.remoteAddress() + "离开了\t"+"当前在线人数:"+channelGroup.size()+"\n"));
        System.out.println("当前在线人数:"+channelGroup.size());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常发生" + cause.getMessage());
        ctx.close();
    }

    //通道就绪时
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(LocalDateTime.now().format(dateTimeFormatter)+"\t"+ctx.channel().remoteAddress() + "上线了...");
    }

    //当通道非活动状态
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(LocalDateTime.now().format(dateTimeFormatter)+"\t"+ctx.channel().remoteAddress() + "离线了...");
    }
}
